package com.xo.xodemo.controller.process;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xo.xodemo.common.Result;
import com.xo.xodemo.mapper.db1.*;
import com.xo.xodemo.model.*;
import com.xo.xodemo.service.FileService;
import com.xo.xodemo.springsecurityconfig.CustomUserDetails;
import com.xo.xodemo.util.MoneyFormatterUtil;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;

@Controller
@RequestMapping("/process")
public class ProcessController {
    @Autowired
    private RefundMapper refundMapper;//退款
    @Autowired
    private ComplaintMapper complaintMapper;
    @Autowired
    private ProcessStatusMapper processStatusMapper;
    @Autowired
    private FileService fileService;
    @Autowired
    private ProofBargainMapper proofBargainMapper;
    @Autowired
    private LeaveMapper leaveMapper;
    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private AttendanceMapper attendanceMapper;
    @Autowired
    private EntryMapper entryMapper;
    @Autowired
    private PurchaseMapper purchaseMapper;
    @Autowired
    private ResignMapper resignMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private  ProcessSettingMapper processSettingMapper;
    @Autowired
    private  ProcessListMapper processListMapper;
    @Autowired
    private  FileMapper fileMapper;
    @Autowired
    private  ComplianceMapper complianceMapper;
    @Autowired
    private  DefaultCopyMapper defaultCopyMapper;
    @Autowired
    private  ReimburseMapper reimburseMapper;
    @Autowired
    private  RegularWorkerMapper regularWorkerMapper;
    @Autowired
    private  HasBeenReadMapper hasBeenReadMapper;//未读消息
    @Autowired
    private LoanMapper loanMapper;//借款单
    @Autowired
    private ThreeSixFivePushMapper push365Mapper;//365推送
    private static SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    //转到请假申请界面
    @RequestMapping ("/leavepage")
    public String leavepage(Model model,@AuthenticationPrincipal CustomUserDetails userDetails) throws IOException {
        Boolean HasTwoSetting=false;
        Boolean isJingLi=false;
        ProcessSetting ps =processSettingMapper.selectbyidandtype(userDetails.getDepartmentId(),12);
        if(null!=ps){
            HasTwoSetting=true;
        }
        List<Integer>positonlist=departmentMapper.findMyJingli();
        if(positonlist.contains(userDetails.getPositionId())){
            isJingLi=true;
        }
        model.addAttribute("userDetails",userDetails);
        model.addAttribute("HasTwoSetting",HasTwoSetting);
        model.addAttribute("isJingLi",isJingLi);
        return "process/leave/leaveaddpage";
    }

    //转到请假申请(一日)界面
    @RequestMapping ("/leaveOnePage")
    public String leaveOnePage(Model model,@AuthenticationPrincipal CustomUserDetails userDetails) throws IOException {
         processBuild(12,userDetails,model);

        return "process/leave/leaveaddpage::auditingPerson";
    }
    private void processBuild(Integer processType,CustomUserDetails userDetails,Model model){
        //先生成一个流程
        String id=UUID.randomUUID().toString().toLowerCase();
        ProcessSetting ps =processSettingMapper.selectbyidandtype(userDetails.getDepartmentId(),processType);
        ProcessEntity pet=new ProcessEntity();
        pet.setId(id);
        pet.setProcessType(processType);
        pet.setAuditerStatus(1);
        pet.setApplyName(userDetails.getUsername());
        pet.setApplyRealName(userMapper.selectName(userDetails.getUsername()));
        pet.setAuditingCount(ps.getAuditingcount());
        pet.setAuditingPersonSetting(ps.getAuditingperson());
        pet.setDepartmentId(userDetails.getDepartmentId());
        pet.setApplyNumber(userDetails.getEmployeeNumber());
        model.addAttribute("id",id);
        model.addAttribute("userDetails",userDetails);
        //根据审核状态查询职位
        String[] strings=ps.getAuditingperson().split("\\|");
        int auditerStatus = 1;
        for (int i = 0; i < strings.length; i++) {
            if (strings[i].equals(String.valueOf(userDetails.getPositionId()))) {
                auditerStatus = i + 2; // 数在数组中的位置（第几个）
                break; // 找到数后立即结束循环
            }
        }
        //如果申请人为流程最后一位，直接成功
        if(auditerStatus>ps.getAuditingcount()){
            auditerStatus=100;
        }
        String positionId=null;
        try {
            positionId=ps.getAuditingperson().split("\\|")[auditerStatus-1];
        }catch (ArrayIndexOutOfBoundsException e){

        }
//        System.out.println(positionId);
        pet.setAuditerStatus(auditerStatus);
        //审核流程到末尾没有选的了
        if(positionId==null){
            //申请的为最后一个，自己审核自己
            pet.setAuditingPerson(userDetails.getUsername());
            model.addAttribute("lb",new ArrayList<BaseUser>());
        }
        List<BaseUser> lb = userMapper.findBypositionId(positionId);
        List<BaseUser> lbcopy =new ArrayList<>();
        lbcopy.addAll(lb);
        //优先匹配本部门的
        Iterator<BaseUser> it=lb.listIterator();
        while (it.hasNext()){
            BaseUser b=it.next();
            if(!b.getDepartmentId().equals(userDetails.getDepartmentId())){
                it.remove();
            }
        }
        //本部门一个没有则不匹配
        if(lb.size()==0){
            model.addAttribute("lb",lbcopy);
        }else {
            model.addAttribute("lb",lb);
        }
        //如果自己就是结尾则自己给自己审核
        if(auditerStatus>=100){
            List<BaseUser> lbown = userMapper.findByUserName(userDetails.getUsername());
            model.addAttribute("lb",lbown);
        }
        processListMapper.insert(pet);
    }
    //转到请假申请(两日以上)界面
    @RequestMapping ("/leaveTwoPage")
    public String leaveTwoPage(Model model,@AuthenticationPrincipal CustomUserDetails userDetails) throws IOException {
        processBuild(13,userDetails,model);
        return "process/leave/leaveaddpage::auditingPerson";
    }
    @RequestMapping ("/leaveOtherPage")
    public String leaveOtherPage(Model model,@AuthenticationPrincipal CustomUserDetails userDetails) throws IOException {
        processBuild(0,userDetails,model);
        return "process/leave/leaveaddpage::auditingPerson";
    }
    //转到异常考勤申请界面
    @RequestMapping ("/attendancepage")
    public String attendancepage(Model model,@AuthenticationPrincipal CustomUserDetails userDetails) throws IOException {
        processBuild(1,userDetails,model);
        return "process/attendance/attendanceaddpage";
    }
    //转到入职申请界面
    @RequestMapping ("/entrypage")
    public String entrypage(Model model,@AuthenticationPrincipal CustomUserDetails userDetails) throws IOException {
        processBuild(2,userDetails,model);
        return "process/entry/entryaddpage";
    }
    //转到转正申请界面
    @RequestMapping ("/regularworkerpage")
    public String regularworkerpage(Model model,@AuthenticationPrincipal CustomUserDetails userDetails) throws IOException {
        processBuild(6,userDetails,model);
        return "process/regularworker/regularworkeraddpage";
    }
    //转到合规申请界面
    @RequestMapping ("/compliancepage")
    public String compliancepage(Model model,@AuthenticationPrincipal CustomUserDetails userDetails) throws IOException {
        processBuild(7,userDetails,model);
        return "process/compliance/complianceaddpage";
    }
    //转到成交单申请界面
    @RequestMapping ("/proofbargainpage")
    public String proofbargain(Model model,@AuthenticationPrincipal CustomUserDetails userDetails) throws IOException {
        processBuild(3,userDetails,model);
        return "process/proofbargain/proofbargainaddpage";
    }
    //转到采购单界面
    @RequestMapping ("/purchasepage")
    public String purchase(Model model,@AuthenticationPrincipal CustomUserDetails userDetails) throws IOException {
        processBuild(4,userDetails,model);
        return "process/purchase/purchaseaddpage";
    }
    //转到离职单申请界面
    @RequestMapping ("/resignpage")
    public String resignpage(Model model,@AuthenticationPrincipal CustomUserDetails userDetails) throws IOException {

        List<Position>lp=resignMapper.findAllJL();
        List<Position>lp1=resignMapper.findAllZHULI();
        for(Position p:lp){
            if(userDetails.getPositionId().equals(p.getPositionId())){
                processBuild(16,userDetails,model);
                return "process/resign/resignaddpage";
            }
        }
        for(Position p:lp1){
            if(userDetails.getPositionId().equals(p.getPositionId())){
                processBuild(17,userDetails,model);
                return "process/resign/resignaddpage";
            }
        }
        processBuild(5,userDetails,model);
        return "process/resign/resignaddpage";
    }
    //转到报销单申请界面
    @RequestMapping ("/reimbursepage")
    public String reimbursepage(Model model,@AuthenticationPrincipal CustomUserDetails userDetails) throws IOException {
        processBuild(11,userDetails,model);
        return "process/reimburse/reimburseaddpage";
    }
    //转到退款单申请界面
    @RequestMapping ("/refundpage")
    public String refundpage(Model model,@AuthenticationPrincipal CustomUserDetails userDetails) throws IOException {
        //先生成一个流程
        String id=UUID.randomUUID().toString().toLowerCase();
        model.addAttribute("id",id);
        model.addAttribute("userDetails",userDetails);
        return "process/refund/refundaddpage";
    }
    //退款单（365）
    @RequestMapping("/refundpage0")
    public String refundpage0(Model model,@AuthenticationPrincipal CustomUserDetails userDetails,
                              @Param("id")String id) throws IOException{
        //先生成一个流程
        ProcessSetting ps =processSettingMapper.selectbyidandtype(userDetails.getDepartmentId(),9);
        ProcessEntity pet=new ProcessEntity();
        pet.setId(id);
        pet.setProcessType(9);
        pet.setAuditerStatus(1);
        pet.setApplyName(userDetails.getUsername());
        pet.setApplyRealName(userMapper.selectName(userDetails.getUsername()));
        pet.setAuditingCount(ps.getAuditingcount());
        pet.setAuditingPersonSetting(ps.getAuditingperson());
        pet.setDepartmentId(userDetails.getDepartmentId());
        pet.setPaymentWay("4");//单据类型

        model.addAttribute("id",id);
        model.addAttribute("userDetails",userDetails);
        //根据审核状态查询职位
        String[] strings=ps.getAuditingperson().split("\\|");
        int auditerStatus = 1;
        for (int i = 0; i < strings.length; i++) {
            if (strings[i].equals(String.valueOf(userDetails.getPositionId()))) {
                auditerStatus = i + 2; // 数在数组中的位置（第几个）
                break; // 找到数后立即结束循环
            }
        }
        //如果申请人为流程最后一位，直接成功
        if(auditerStatus>ps.getAuditingcount()){
            auditerStatus=100;
        }
        String positionId=null;
        try {
            positionId=ps.getAuditingperson().split("\\|")[auditerStatus-1];
        }catch (ArrayIndexOutOfBoundsException e){

        }
        pet.setAuditerStatus(auditerStatus);
        //审核流程到末尾没有选的了
        if(positionId==null){
            //申请的为最后一个，自己审核自己
            pet.setAuditingPerson(userDetails.getUsername());
            model.addAttribute("lb",new ArrayList<BaseUser>());
        }
        List<BaseUser> lb = userMapper.findBypositionId(positionId);
        List<BaseUser> lbcopy =new ArrayList<>();
        lbcopy.addAll(lb);
        //优先匹配本部门的
        Iterator<BaseUser> it=lb.listIterator();
        while (it.hasNext()){
            BaseUser b=it.next();
            if(!b.getDepartmentId().equals(userDetails.getDepartmentId())){
                it.remove();
            }
        }
        //本部门一个没有则不匹配
        if(lb.size()==0){
            model.addAttribute("lb",lbcopy);
        }else {
            model.addAttribute("lb",lb);
        }
        //如果自己就是结尾则自己给自己审核
        if(auditerStatus>=100){
            List<BaseUser> lbown = userMapper.findByUserName(userDetails.getUsername());
            model.addAttribute("lb",lbown);
        }
        processListMapper.insert(pet);
        return "process/refund/refundaddpage::auditingPerson";
    }
    //退款单（大额）
    @RequestMapping("/refundpage1")
    public String refundpage1(Model model,@AuthenticationPrincipal CustomUserDetails userDetails,
                              @Param("id")String id) throws IOException{
        //先生成一个流程
        ProcessSetting ps =processSettingMapper.selectbyidandtype(userDetails.getDepartmentId(),10);
        ProcessEntity pet=new ProcessEntity();
        pet.setId(id);
        pet.setProcessType(10);
        pet.setAuditerStatus(1);
        pet.setApplyName(userDetails.getUsername());
        pet.setApplyRealName(userMapper.selectName(userDetails.getUsername()));
        pet.setAuditingCount(ps.getAuditingcount());
        pet.setAuditingPersonSetting(ps.getAuditingperson());
        pet.setDepartmentId(userDetails.getDepartmentId());
        pet.setPaymentWay("5");//单据类型

        model.addAttribute("id",id);
        model.addAttribute("userDetails",userDetails);
        //根据审核状态查询职位
        String[] strings=ps.getAuditingperson().split("\\|");
        int auditerStatus = 1;
        for (int i = 0; i < strings.length; i++) {
            if (strings[i].equals(String.valueOf(userDetails.getPositionId()))) {
                auditerStatus = i + 2; // 数在数组中的位置（第几个）
                break; // 找到数后立即结束循环
            }
        }
        //如果申请人为流程最后一位，直接成功
        if(auditerStatus>ps.getAuditingcount()){
            auditerStatus=100;
        }
        String positionId=null;
        try {
            positionId=ps.getAuditingperson().split("\\|")[auditerStatus-1];
        }catch (ArrayIndexOutOfBoundsException e){

        }
        pet.setAuditerStatus(auditerStatus);
        //审核流程到末尾没有选的了
        if(positionId==null){
            //申请的为最后一个，自己审核自己
            pet.setAuditingPerson(userDetails.getUsername());
            model.addAttribute("lb",new ArrayList<BaseUser>());
        }
        List<BaseUser> lb = userMapper.findBypositionId(positionId);
        List<BaseUser> lbcopy =new ArrayList<>();
        lbcopy.addAll(lb);
        //优先匹配本部门的
        Iterator<BaseUser> it=lb.listIterator();
        while (it.hasNext()){
            BaseUser b=it.next();
            if(!b.getDepartmentId().equals(userDetails.getDepartmentId())){
                it.remove();
            }
        }
        //本部门一个没有则不匹配
        if(lb.size()==0){
            model.addAttribute("lb",lbcopy);
        }else {
            model.addAttribute("lb",lb);
        }
        //如果自己就是结尾则自己给自己审核
        if(auditerStatus>=100){
            List<BaseUser> lbown = userMapper.findByUserName(userDetails.getUsername());
            model.addAttribute("lb",lbown);
        }
        processListMapper.insert(pet);
        return "process/refund/refundaddpage::auditingPerson";
    }
    //转到借款单申请界面
    @RequestMapping ("/loanpage")
    public String loanpage(Model model,@AuthenticationPrincipal CustomUserDetails userDetails) throws IOException {
        processBuild(15,userDetails,model);
        model.addAttribute("department",userMapper.findPositonDepartmentNameByName(userDetails.getUsername()).getDepartmentName());
        return "process/loan/loanaddpage";
    }

    //我的申请
    @RequestMapping ("/myprocess")
    @ResponseBody
    public Result myprocess(@AuthenticationPrincipal CustomUserDetails userDetails,@Param("page") Integer page, @Param("limit")Integer limit) throws IOException {
        PageHelper.startPage(page,limit);
         PageInfo<ProcessEntity> pi = new PageInfo<>(processListMapper.selectmy(userDetails.getUsername()))  ;
         return    Result.success(pi);
    }

    //我的未完成审核
    @RequestMapping("/myunfinishedprocessauditing")
    @ResponseBody
    public Result myunfinishedprocessauditing(
            @AuthenticationPrincipal CustomUserDetails userDetails,
            @Param("page") Integer page, @Param("limit") Integer limit,
            @Param("applyRealName") String applyRealName,
            @Param("applyTimeStart") String applyTimeStart,
            @Param("applyTimeEnd") String applyTimeEnd,
            @Param("name") String name,
            @Param("telephone") String telephone,
            @Param("paymentMethod") String paymentMethod,
            @Param("transferDateStart") String transferDateStart,
            @Param("transferDateEnd") String transferDateEnd,
            @Param("processType") String processType
    ) throws IOException {
        //判断转账日期的起始值是否为空，为空赋值
        if (transferDateStart == null || transferDateStart.isEmpty()) {
            if (transferDateEnd != null && transferDateEnd != ""){
                transferDateStart = "0000-00-00";
            }
        }
        if (transferDateEnd == null || transferDateEnd.isEmpty()){
            if(transferDateStart != null && transferDateStart != ""){
                transferDateEnd = "8888-12-31";
            }
        }
        PageHelper.startPage(page, limit);
        PageInfo<ProcessEntity> pi = new PageInfo<>(processListMapper.selectUnFinishedForMe(userDetails.getUsername(), applyRealName,
                applyTimeStart, applyTimeEnd, name, telephone,
                paymentMethod, transferDateStart, transferDateEnd,
                processType));

        List<ProcessEntity> list = pi.getList();
        List<ProcessEntity> newList = new ArrayList<>();
        // 处理已读消息
        List<HasBeenReadModel> hasBeenReadList = hasBeenReadMapper.selectHasBeenRead(userDetails.getUsername());
        for (ProcessEntity processEntity : list) {
            for (HasBeenReadModel hasBeenReadModel : hasBeenReadList) {
                if (hasBeenReadModel.getMessageType().equals("1") && processEntity.getId().equals(hasBeenReadModel.getMessageId())) {
                    processEntity.setIsRead(0);
                    break;
                }
            }
            newList.add(processEntity);
        }
        // 添加用户位置信息
        for (ProcessEntity entity : newList) {
            entity.setPositionId(userDetails.getPositionId());
        }
        pi.setList(newList);
        return Result.success(pi);
    }

    //我的已完成审核
    @RequestMapping ("/myfinishedprocessauditing")
    @ResponseBody
    public Result myfinishedprocessauditing(
            @AuthenticationPrincipal CustomUserDetails userDetails,
            @Param("page") Integer page, @Param("limit")Integer limit,
            @Param("applyRealName") String applyRealName,
            @Param("applyTimeStart") String applyTimeStart,
            @Param("applyTimeEnd") String applyTimeEnd,
            @Param("name")String name,
            @Param("telephone")String telephone,
            @Param("paymentMethod")String paymentMethod,
            @Param("transferDateStart")String transferDateStart,
            @Param("transferDateEnd")String transferDateEnd,
            @Param("processType")String processType
    )throws IOException {
        //判断转账日期的起始值是否为空，为空赋值
        if (transferDateStart == null || transferDateStart.isEmpty()) {
            if (transferDateEnd != null && transferDateEnd != ""){
                transferDateStart = "0000-00-00";
            }
        }
        if (transferDateEnd == null || transferDateEnd.isEmpty()){
            if(transferDateStart != null && transferDateStart != ""){
                transferDateEnd = "8888-12-31";
            }
        }
        PageHelper.startPage(page,limit);
        PageInfo<ProcessEntity> pi = new PageInfo<>(processListMapper.selectFinishedForMe(userDetails.getUsername(),applyRealName,
                                                                                            applyTimeStart,applyTimeEnd,name,telephone,
                                                                                            paymentMethod,transferDateStart,transferDateEnd,
                                                                                            processType));
        List<HasBeenReadModel> hasBeenReadList = hasBeenReadMapper.selectHasBeenRead(userDetails.getUsername());//给消息未读的小红点用
        List<ProcessEntity> list = pi.getList();
        List<ProcessEntity> newList = new ArrayList<>();
        for (int listSize = 0 ;listSize < list.size();listSize++){
            ProcessEntity processEntity = (ProcessEntity) list.get(listSize);
            for (HasBeenReadModel hasBeenReadModel:hasBeenReadList){
                if (hasBeenReadModel.getMessageType().equals("2")){
                    if (processEntity.getId().equals(hasBeenReadModel.getMessageId())){
                        processEntity.setIsRead(0);
                    }
                }
            }
            newList.add(processEntity);
        }
        pi.setList(newList);
        return    Result.success(pi);
    }
    //抄送给我的
    @RequestMapping ("/copyforme")
    @ResponseBody
    public Result copyforme(
            @AuthenticationPrincipal CustomUserDetails userDetails,
            @Param("page") Integer page, @Param("limit")Integer limit,
            @Param("applyRealName") String applyRealName,
            @Param("applyTimeStart") String applyTimeStart,
            @Param("applyTimeEnd") String applyTimeEnd,
            @Param("name")String name,
            @Param("telephone")String telephone,
            @Param("paymentMethod")String paymentMethod,
            @Param("transferDateStart")String transferDateStart,
            @Param("transferDateEnd")String transferDateEnd,
            @Param("processType")String processType
    ) throws IOException {
        //判断转账日期的起始值是否为空，为空赋值
        if (transferDateStart == null || transferDateStart.isEmpty()) {
            if (transferDateEnd != null && transferDateEnd != ""){
                transferDateStart = "0000-00-00";
            }
        }
        if (transferDateEnd == null || transferDateEnd.isEmpty()){
            if(transferDateStart != null && transferDateStart != ""){
                transferDateEnd = "8888-12-31";
            }
        }
        PageHelper.startPage(page,limit);
        PageInfo<ProcessEntity> pi = new PageInfo<>(processListMapper.selectCopyForMe(userDetails.getUsername(),applyRealName,
                                                                                        applyTimeStart,applyTimeEnd,name,telephone,
                                                                                        paymentMethod,transferDateStart,transferDateEnd,
                                                                                        processType));
        List<HasBeenReadModel> hasBeenReadList = hasBeenReadMapper.selectHasBeenRead(userDetails.getUsername());//给消息未读的小红点用
        List<ProcessEntity> list = pi.getList();
        List<ProcessEntity> newList = new ArrayList<>();
        for (int listSize = 0 ;listSize < list.size();listSize++){
            ProcessEntity processEntity = (ProcessEntity) list.get(listSize);
            for (HasBeenReadModel hasBeenReadModel:hasBeenReadList){
                if (hasBeenReadModel.getMessageType().equals("3")){
                    if (processEntity.getId().equals(hasBeenReadModel.getMessageId())){
                        processEntity.setIsRead(0);
                    }
                }
            }
            newList.add(processEntity);
        }
        pi.setList(newList);
        return    Result.success(pi);
    }

    //转到成交单补款页面
    @RequestMapping("/paymentSwitch")
    public String paymentSwitch (@AuthenticationPrincipal CustomUserDetails userDetails,@RequestParam(value = "isauditing",defaultValue = "0") String isauditing,String id,Integer processType,Model model) throws IOException {
        ProcessEntity pe=processListMapper.selectById(id);
        String positionId="8";
        List<BaseUser> lb= userMapper.findBypositionId(positionId);
        String[] parts = pe.getAuditingPerson().split("\\|");
        if(!parts[parts.length-1].equals(userDetails.getUsername())||pe.getAuditerStatus()>=100){
            isauditing="0";
        }
        model.addAttribute("lb",lb);
        model.addAttribute("copyperson",processListMapper.getCopyPerson(id));
        model.addAttribute("isauditing",isauditing);
        model.addAttribute("process",processListMapper.selectById(id));
        model.addAttribute("ProofBargain",proofBargainMapper.selectById(id));
        model.addAttribute("ProcessEntity",processListMapper.selectById(id));

        return "process/proofbargain/proofbargainwaypage";
    }


    //转到成交单修改页面
    @RequestMapping("/proofbargainupdateadd")
    public String proofbargainupdateadd(@AuthenticationPrincipal CustomUserDetails userDetails,@RequestParam(value = "isauditing",defaultValue = "0") String isauditing,String id,Integer processType,Model model) throws IOException {
        ProcessEntity pe=processListMapper.selectById(id);
        String positionId="8";
        List<BaseUser> lb= userMapper.findBypositionId(positionId);
        String[] parts = pe.getAuditingPerson().split("\\|");
        if(!parts[parts.length-1].equals(userDetails.getUsername())||pe.getAuditerStatus()>=100){
            isauditing="0";
        }
        model.addAttribute("lb",lb);
        model.addAttribute("copyperson",processListMapper.getCopyPerson(id));
        model.addAttribute("isauditing",isauditing);
        model.addAttribute("process",processListMapper.selectById(id));
        model.addAttribute("ProofBargain",proofBargainMapper.selectById(id));
        model.addAttribute("ProcessEntity",processListMapper.selectById(id));

        return "process/proofbargain/proofbargainupdatepage";
    }


    //修改消息是否已读
    @RequestMapping("/updateIsRead")
    @ResponseBody
    public Result updateIsRead(@Param("isRead") Integer isRead, @Param("id")String id){
        if (id != null){
            processListMapper.updateIsRead(isRead,id);
        }
        return  Result.success();
    }
    //通过id查询审核状态
    @RequestMapping("/selectAuditerStatusById")
    @ResponseBody
    public Integer selectAuditerStatusById(@Param("id")String id){
        Integer auditerStatus = -1;
        if (id != null){
          auditerStatus =  processListMapper.selectAuditerStatusById(id);
        }
        return auditerStatus;
    }
    //流程详情
    @RequestMapping ("/processdetailpage")
    public String processdetailpage(@AuthenticationPrincipal CustomUserDetails userDetails,@RequestParam(value = "isauditing",defaultValue = "0") String isauditing,String id,Integer processType,Model model) throws IOException {
        ProcessEntity pe=processListMapper.selectById(id);
        String positionId=getauditingposition(pe.getAuditerStatus(),pe.getAuditingPersonSetting());
        List<BaseUser> lb= userMapper.findBypositionId(positionId);
        String[] parts = pe.getAuditingPerson().split("\\|");
        if(!parts[parts.length-1].equals(userDetails.getUsername())||pe.getAuditerStatus()>=100){
            isauditing="0";
        }
        model.addAttribute("lb",lb);
        model.addAttribute("copyperson",processListMapper.getCopyPerson(id));
        model.addAttribute("isauditing",isauditing);
        model.addAttribute("process",processListMapper.selectById(id));
        if(processType==0||processType==12||processType==13){
            model.addAttribute("leavemodel",leaveMapper.selectById(id));
            model.addAttribute("StatusEntity",processStatusMapper.selectById(id));
            return "process/leave/leavedetailpage";
        }
        if(processType==1){
            model.addAttribute("AttendanceModel",attendanceMapper.selectById(id));
            model.addAttribute("StatusEntity",processStatusMapper.selectById(id));
            return "process/attendance/attendancedetailpage";
        }
        if(processType==2){
            model.addAttribute("EntryModel",entryMapper.selectById(id));
            model.addAttribute("StatusEntity",processStatusMapper.selectById(id));
            return "process/entry/entrydetailpage";
        }
        if(processType==3 || processType==8){
            model.addAttribute("ProofBargain",proofBargainMapper.selectById(id));
            model.addAttribute("StatusEntity",processStatusMapper.selectById(id));
            return "process/proofbargain/proofbargaindetailpage";
        }
        if(processType==4){
            String[] listforModify=purchaseMapper.findLoanModifyUsers().split("\\|");
            model.addAttribute("isPurchaseModifyUser","false");
            for (String str : listforModify) {
                if (str.equals(userDetails.getUsername())) {
                    model.addAttribute("isPurchaseModifyUser","true");
                    break;
                }}
            model.addAttribute("PurchaseModel",purchaseMapper.selectById(id));
            model.addAttribute("StatusEntity",processStatusMapper.selectById(id));
            return "process/purchase/purchasedetailpage";
        }
        if(processType==5||processType==16||processType==17){
            model.addAttribute("ResignModel",resignMapper.selectById(id));
            model.addAttribute("StatusEntity",processStatusMapper.selectById(id));
            return "process/resign/resigndetailpage";
        }
        if(processType==6){
            model.addAttribute("RegularWorkerModel",regularWorkerMapper.selectById(id));
            model.addAttribute("StatusEntity",processStatusMapper.selectById(id));
            return "process/regularworker/regularworkerdetailpage";
        }
        if(processType==7){
            model.addAttribute("ComplianceModel",complianceMapper.selectById(id));
            model.addAttribute("FileModel",fileMapper.selectFileByProcessId(id));
            model.addAttribute("StatusEntity",processStatusMapper.selectById(id));
            return "process/compliance/compliancedetailpage";
        }
        if (processType==9){
            //退款365
            model.addAttribute("RefundModel",refundMapper.selectById(id));
            model.addAttribute("StatusEntity",processStatusMapper.selectById(id));
            return "process/refund/refunddetailpage";
        }
        if (processType==10){
            //退款大额
            model.addAttribute("RefundModel",refundMapper.selectById(id));
            model.addAttribute("StatusEntity",processStatusMapper.selectById(id));
            return "process/refund/refunddetailpage";
        }
        if(processType==11){
            ReimburseModel rm=reimburseMapper.selectById(id);
            model.addAttribute("ReimburseModel",reimburseMapper.selectById(id));
            model.addAttribute("FormatterMoney",MoneyFormatterUtil.formatAmount(rm.getMoney()));
            model.addAttribute("FileModel",fileMapper.selectFileByProcessId(id));
            model.addAttribute("StatusEntity",processStatusMapper.selectById(id));
            return "process/reimburse/reimbursedetailpage";
        }
        if(processType==14){
            model.addAttribute("ComplaintEntity",complaintMapper.selectById(id));
            model.addAttribute("StatusEntity",processStatusMapper.selectById(id));
            //添加审核人
            ProcessSetting ps =processSettingMapper.selectbyidandtype(userDetails.getDepartmentId(),14);
            String[] ids = ps.getAuditingperson().split("\\|"); // 按照 "|" 分割字符串
            List<BaseUser> lbcopy = new ArrayList<>(); // 在循环外部初始化 lbcopy
            for (String idd : ids) {
                lb = userMapper.findBypositionId(idd);
                lbcopy.addAll(lb);
            }
            model.addAttribute("lb", lbcopy);

            return "process/complaint/complaintdetailpage";
        }
        if (processType==15){
            //借款单
            LoanModel lm = loanMapper.selectById(id);
            model.addAttribute("StatusEntity",processStatusMapper.selectById(id));
            model.addAttribute("LoanModel",lm);
            model.addAttribute("FormatterMoney",MoneyFormatterUtil.formatAmount(lm.getLoanAmount()));
            return "process/loan/loandetailpage";
        }
        return  "process/leave/leavedetailpage";
    }
    //异常考勤提交接口
    @RequestMapping ("/attendanceadd")
    public String attendanceadd(@Param("filePath") MultipartFile filePath , AttendanceModel attendanceModel, @AuthenticationPrincipal CustomUserDetails userDetails,Model model) throws IOException, ParseException {
        processListMapper.addPersonAndRealName(attendanceModel.getAuditingPerson(),userMapper.selectName(attendanceModel.getAuditingPerson()),attendanceModel.getId(), attendanceModel.getPaymentWay());
        //文件储存
        if(filePath!=null){
            String realaddress=   fileService.transfer(filePath);
            //存储异常考勤单
            attendanceModel.setFileAddress(realaddress);
        }
        model.addAttribute("tanchuang","yes");
        ReturnUser ru=userMapper.findPositonDepartmentNameByName(userDetails.getUsername());
        attendanceModel.setPositionName(ru.getPositionName());
        attendanceModel.setDepartmentName(ru.getDepartmentName());
        attendanceMapper.insert(attendanceModel);

        // 时间轴相关 在创建单据时插入第一个审核人
        LocalDateTime currentTime = LocalDateTime.now();
        DateTimeFormatter formDate = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        String formDateTime = currentTime.format(formDate);
        String text1 = formDateTime + "; " + userMapper.selectName(attendanceModel.getAuditingPerson());
        processStatusMapper.statusInsert(attendanceModel.getId(),text1);

    //为了记录未读消息提醒(messageType = "1")
        ProcessEntity processEntityForUnreadMessage = processListMapper.selectById(attendanceModel.getId());
        if (processEntityForUnreadMessage.getAuditerStatus() != 100){
            List hasBeenReadModelList = new ArrayList<>();
            HasBeenReadModel hasBeenReadModel  = new HasBeenReadModel();
            hasBeenReadModel.setUsername(attendanceModel.getAuditingPerson());
            hasBeenReadModel.setMessageId(attendanceModel.getId());
            hasBeenReadModel.setMessageType("1");
            hasBeenReadModelList.add(hasBeenReadModel);
            hasBeenReadMapper.addHasBeenReads(hasBeenReadModelList);
        }
        return  "process/processadd";
    }
    //入职提交接口
    @RequestMapping ("/entryadd")
    public String entryadd(@Param("filePath") MultipartFile filePath , EntryModel entryModel,@AuthenticationPrincipal CustomUserDetails userDetails,Model model,@Param("copyPersons")String copyPersons) throws IOException, ParseException {
        JSONArray ja=JSONArray.parseArray(copyPersons);
        List<String> copyPersonsLs=new ArrayList<>();
        for(int i=0;i<ja.size();i++){
            JSONObject jsonObject =ja.getJSONObject(i);
            copyPersonsLs.add(jsonObject.getString("value"));
        }
        processListMapper.addPersonAndRealName(entryModel.getAuditingPerson(),userMapper.selectName(entryModel.getAuditingPerson()),entryModel.getId(), entryModel.getPaymentWay());
        if(filePath!=null){
            String realaddress = fileService.transfer(filePath);
            entryModel.setFileAddress(realaddress);
        }
        processListMapper.upsertCopy(copyPersonsLs,entryModel.getId());
        model.addAttribute("tanchuang","yes");
        ReturnUser ru=userMapper.findPositonDepartmentNameByName(userDetails.getUsername());
        entryModel.setPositionName(ru.getPositionName());
        entryModel.setDepartmentName(ru.getDepartmentName());
        entryMapper.insert(entryModel);

        // 时间轴相关 在创建单据时插入第一个审核人
        LocalDateTime currentTime = LocalDateTime.now();
        DateTimeFormatter formDate = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        String formDateTime = currentTime.format(formDate);
        String text1 = formDateTime + "; " + userMapper.selectName(entryModel.getAuditingPerson());
        processStatusMapper.statusInsert(entryModel.getId(),text1);

        //为了记录未读消息提醒(messageType = "3")
        if(copyPersonsLs.size() != 0){
            List hasBeenReadModelListCP = new ArrayList<>();
            for (String cp:copyPersonsLs){
                HasBeenReadModel hasBeenReadModelCP  = new HasBeenReadModel();
                hasBeenReadModelCP.setUsername(cp);
                hasBeenReadModelCP.setMessageId(entryModel.getId());
                hasBeenReadModelCP.setMessageType("3");
                hasBeenReadModelListCP.add(hasBeenReadModelCP);
            }
            hasBeenReadMapper.addHasBeenReads(hasBeenReadModelListCP);
        }
        //为了记录未读消息提醒(messageType = "1")
        ProcessEntity processEntityForUnreadMessage = processListMapper.selectById(entryModel.getId());
        if (processEntityForUnreadMessage.getAuditerStatus() != 100) {
            List hasBeenReadModelList = new ArrayList<>();
            HasBeenReadModel hasBeenReadModel = new HasBeenReadModel();
            hasBeenReadModel.setUsername(entryModel.getAuditingPerson());
            hasBeenReadModel.setMessageId(entryModel.getId());
            hasBeenReadModel.setMessageType("1");
            hasBeenReadModelList.add(hasBeenReadModel);
            hasBeenReadMapper.addHasBeenReads(hasBeenReadModelList);
        }
        return  "process/processadd";
    }
    //转正申请提交接口
    @RequestMapping ("/regularworkeradd")
    public String regularworkeradd(@Param("filePath") MultipartFile filePath , RegularWorkerModel regularWorkerModel,@AuthenticationPrincipal CustomUserDetails userDetails,Model model) throws IOException, ParseException {
        processListMapper.addPersonAndRealName(regularWorkerModel.getAuditingPerson(),userMapper.selectName(regularWorkerModel.getAuditingPerson()),regularWorkerModel.getId(), regularWorkerModel.getPaymentWay());
        if(filePath!=null){
            String realaddress=   fileService.transfer(filePath);
            //存储采购单
            regularWorkerModel.setFileAddress(realaddress);
        }
        model.addAttribute("tanchuang","yes");
        ReturnUser ru=userMapper.findPositonDepartmentNameByName(userDetails.getUsername());
        regularWorkerModel.setPositionName(ru.getPositionName());
        regularWorkerModel.setDepartmentName(ru.getDepartmentName());
        regularWorkerMapper.insert(regularWorkerModel);

        // 时间轴相关 在创建单据时插入第一个审核人
        LocalDateTime currentTime = LocalDateTime.now();
        DateTimeFormatter formDate = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        String formDateTime = currentTime.format(formDate);
        String text1 = formDateTime + "; " + userMapper.selectName(regularWorkerModel.getAuditingPerson());
        processStatusMapper.statusInsert(regularWorkerModel.getId(),text1);

        //为了记录未读消息提醒(messageType = "1")
        ProcessEntity processEntityForUnreadMessage = processListMapper.selectById(regularWorkerModel.getId());
        if (processEntityForUnreadMessage.getAuditerStatus() != 100) {
            List hasBeenReadModelList = new ArrayList<>();
            HasBeenReadModel hasBeenReadModel = new HasBeenReadModel();
            hasBeenReadModel.setUsername(regularWorkerModel.getAuditingPerson());
            hasBeenReadModel.setMessageId(regularWorkerModel.getId());
            hasBeenReadModel.setMessageType("1");
            hasBeenReadModelList.add(hasBeenReadModel);
            hasBeenReadMapper.addHasBeenReads(hasBeenReadModelList);
        }
        return  "process/processadd";
    }
    //请假单提交接口
    @RequestMapping ("/leaveadd")
    public String leaveadd(@RequestParam("filePath") MultipartFile filePath , LeaveModel leaveModel,@AuthenticationPrincipal CustomUserDetails userDetails,Model model) throws IOException, ParseException {

        processListMapper.addPersonAndRealName(leaveModel.getAuditingPerson(),userMapper.selectName(leaveModel.getAuditingPerson()),leaveModel.getId(), leaveModel.getPaymentWay());
        //文件储存
        String realaddress=   fileService.transfer(filePath);
        model.addAttribute("tanchuang","yes");
        //存储请假单
        leaveModel.setFileAddress(realaddress);
        ReturnUser ru=userMapper.findPositonDepartmentNameByName(userDetails.getUsername());
        leaveModel.setPositionName(ru.getPositionName());
        leaveModel.setDepartmentName(ru.getDepartmentName());
        leaveMapper.insert(leaveModel);

        // 时间轴相关 在创建单据时插入第一个审核人
        LocalDateTime currentTime = LocalDateTime.now();
        DateTimeFormatter formDate = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        String formDateTime = currentTime.format(formDate);
        String text1 = formDateTime + "; " + userMapper.selectName(leaveModel.getAuditingPerson());
        processStatusMapper.statusInsert(leaveModel.getId(),text1);

        //为了记录未读消息提醒(messageType = "1")
        ProcessEntity processEntityForUnreadMessage = processListMapper.selectById(leaveModel.getId());
        if (processEntityForUnreadMessage.getAuditerStatus() != 100) {
            List hasBeenReadModelList = new ArrayList<>();
            HasBeenReadModel hasBeenReadModel = new HasBeenReadModel();
            hasBeenReadModel.setUsername(leaveModel.getAuditingPerson());
            hasBeenReadModel.setMessageId(leaveModel.getId());
            hasBeenReadModel.setMessageType("1");
            hasBeenReadModelList.add(hasBeenReadModel);
            hasBeenReadMapper.addHasBeenReads(hasBeenReadModelList);
        }
        //判断审核状态是不是100是不是请假单1（是100就是自己为流程的最后一个，自动通过了）
        ProcessEntity processEntityForAuditerStatus = processListMapper.selectById(leaveModel.getId());
        if (processEntityForAuditerStatus.getAuditerStatus().equals(100)&&processEntityForAuditerStatus.getProcessType()==0){
            //一.如果经理以上级别的人，自己结尾，自己提交的请假单自动抄送给总经理
            //存放经理以上级别的职位编号
            List<Integer> specialLeaves = new ArrayList() {{
                //区域经理
                add(4);add(9);
                //部门经理
                add(5);add(10);add(14);add(18);add(22);add(25);add(27);add(31);add(35);add(43);
            }};
            List<String> listforCop = new ArrayList<>();//存放需要抄送给的人的名字
            //查询申请人的职位（进而判断申请人的职位是否满足经理以上级别）
            List<BaseUser> lbown = userMapper.findByUserName(userDetails.getUsername());
            for (BaseUser baseUser:lbown){
                for (Integer specialPositionId:specialLeaves){
                    //如果申请人的职位在经理以上级别
                    if (baseUser.getPositionId().equals(specialPositionId)){
                        //查询总经理
                        List<BaseUser> generalManager =  userMapper.findBypositionId("1");
                        //获取总经理的username
                        for (BaseUser b:generalManager){
                            listforCop.add(b.getUsername());
                        }
                        //将总经理加入到抄送中
                        if (listforCop.size()!= 0){
                            processListMapper.upsertCopy(listforCop,leaveModel.getId());

                            //为了记录未读消息提醒(messageType = "3")
                            List hasBeenReadModelListCP = new ArrayList<>();
                            for (String cp:listforCop){
                                HasBeenReadModel hasBeenReadModelCP  = new HasBeenReadModel();
                                hasBeenReadModelCP.setUsername(cp);
                                hasBeenReadModelCP.setMessageId(leaveModel.getId());
                                hasBeenReadModelCP.setMessageType("3");
                                hasBeenReadModelListCP.add(hasBeenReadModelCP);
                            }
                            hasBeenReadMapper.addHasBeenReads(hasBeenReadModelListCP);
                        }
                    }
                }
            }
        }
        return  "process/processadd";
    }


    //成交单提交接口
    @RequestMapping("/proofbargainadd")
    public String proofbargainadd(@RequestParam("filePath") MultipartFile[] filePath , ProofBargain proofBargain, @AuthenticationPrincipal CustomUserDetails userDetails, Model model) throws IOException, ParseException {
        processListMapper.addPersonAndRealName(proofBargain.getAuditingPerson(), userMapper.selectName(proofBargain.getAuditingPerson()), proofBargain.getId(), proofBargain.getPaymentWay());
//        System.out.println("898, proofBargain = " + proofBargain );
        //文件储存
        StringBuilder fileAddresses = new StringBuilder();
        for(MultipartFile file:filePath){
            String realaddress= fileService.transfer(file);
            fileAddresses.append(realaddress).append("|");
        }
        if (fileAddresses.length() > 0) {
            fileAddresses.setLength(fileAddresses.length() - 1); // 去掉最后一个"|"
        }
        proofBargain.setFileAddress(fileAddresses.toString());
        model.addAttribute("tanchuang", "yes");
        //存储成交单
        ReturnUser ru = userMapper.findPositonDepartmentNameByName(userDetails.getUsername());
        proofBargain.setPositionName(ru.getPositionName());
        proofBargain.setDepartmentName(ru.getDepartmentName());
        proofBargainMapper.insert(proofBargain);

        // 时间轴相关 在创建单据时插入第一个审核人
        LocalDateTime currentTime = LocalDateTime.now();
        DateTimeFormatter formDate = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        String formDateTime = currentTime.format(formDate);
        String text1 = formDateTime + "; " + userMapper.selectName(proofBargain.getAuditingPerson());
        processStatusMapper.statusInsert(proofBargain.getId(),text1);

        //为了记录未读消息提醒(messageType = "1")
        ProcessEntity processEntityForUnreadMessage = processListMapper.selectById(proofBargain.getId());
        if (processEntityForUnreadMessage.getAuditerStatus() != 100) {
            List hasBeenReadModelList = new ArrayList<>();
            HasBeenReadModel hasBeenReadModel = new HasBeenReadModel();
            hasBeenReadModel.setUsername(proofBargain.getAuditingPerson());
            hasBeenReadModel.setMessageId(proofBargain.getId());
            hasBeenReadModel.setMessageType("1");
            hasBeenReadModelList.add(hasBeenReadModel);
            hasBeenReadMapper.addHasBeenReads(hasBeenReadModelList);
        }
        return "process/processadd";
    }


    //补款提交接口(成交单)
    @RequestMapping("/proofbargainupdate")
    public String proofbargainupdate(Model model,@RequestParam("filePath") MultipartFile[] filePath, ProofBargain proofBargain, @AuthenticationPrincipal CustomUserDetails userDetails) throws IOException, ParseException {
        processListMapper.updateaddPersonAndRealName(proofBargain.getAuditingPerson(), userMapper.selectName(proofBargain.getAuditingPerson()), proofBargain.getId(), proofBargain.getPaymentWay());
//        System.out.println("filePath = " + Arrays.deepToString(filePath) + ", proofBargain = " + proofBargain + ", userDetails = " + userDetails);
        StringBuilder fileAddresses = new StringBuilder();
        for (MultipartFile file: filePath) {
            String realaddress = fileService.transfer(file);
            fileAddresses.append(realaddress).append("|");
        }
        if (fileAddresses.length() > 0) {
            fileAddresses.setLength(fileAddresses.length() - 1); // 去掉最后一个"|"
        }
        proofBargain.setFileAddress(fileAddresses.toString());
        model.addAttribute("tanchuang", "yes");
        // 存储成交单
        ReturnUser ru = userMapper.findPositonDepartmentNameByName(userDetails.getUsername());
        proofBargain.setPositionName(ru.getPositionName());
        proofBargain.setDepartmentName(ru.getDepartmentName());
        if (proofBargain.getPaymentWay().equals("1")){ //判断是否为"1"
            proofBargain.setInvoice(proofBargain.getInvoice());
            proofBargain.setContract(proofBargain.getContract());
        }else {
            proofBargain.setInvoice(null);
            proofBargain.setContract(null);
        }
        proofBargainMapper.updateById(proofBargain);


        /*=====================时间轴相关部分=======================*/
        LocalDateTime currentTime = LocalDateTime.now();
        DateTimeFormatter formDate = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        String formDateTime = currentTime.format(formDate);

        String textNameValue = formDateTime + "; " + userMapper.selectName(proofBargain.getAuditingPerson());
        String textNameValue1 = formDateTime + "; " + userDetails.getRealName(); //提交人
        String statusNameValue = "3";
        //根据ID查询投诉单据
        StatusEntity statusEntity = processStatusMapper.selectById(proofBargain.getId());
        // 寻找一组空字段text与img进行插入
        int groupIndexone = 2;
        String textName = "text" + groupIndexone;
        String statusName = "status" + groupIndexone;

        try {
            while (true) {
                Field textField = StatusEntity.class.getDeclaredField(textName);
                textField.setAccessible(true); // 设置字段可访问
                Field statusField = StatusEntity.class.getDeclaredField(statusName);
                statusField.setAccessible(true);

                if (textField.get(statusEntity) == null && statusField.get(statusEntity) == null) {
                    // 将获取到的textValue和imgValue插入到一组空字段中
                    textField.set(statusEntity, textNameValue1);
                    statusField.set(statusEntity, "1");

                    // 找到一组空字段后，再找下一组空字段
                    groupIndexone++;
                    textName = "text" + groupIndexone;
                    statusName = "status" + groupIndexone;

                    // 判断下一组字段是否为空，如果为空则赋值
                    Field nextTextField = StatusEntity.class.getDeclaredField(textName);
                    nextTextField.setAccessible(true);
                    Field nextStatusField = StatusEntity.class.getDeclaredField(statusName);
                    nextStatusField.setAccessible(true);

                    if (nextTextField.get(statusEntity) == null && nextStatusField.get(statusEntity) == null) {
                        // 下一组字段为空，赋予特定的值
                        nextTextField.set(statusEntity, textNameValue);
                        nextStatusField.set(statusEntity, statusNameValue);
                    }

                    break; // 找到空字段并插入后结束循环
                }

                groupIndexone++;
                textName = "text" + groupIndexone;
                statusName = "status" + groupIndexone;
            }
        } catch (Exception e) {
            e.printStackTrace(); // 处理异常
        }

        // 保存更新后的单据
        processStatusMapper.updateStatus(statusEntity, proofBargain.getId());

        /*=====================时间轴相关部分end=======================*/

        //为了记录未读消息提醒(messageType = "1")
        ProcessEntity processEntityForUnreadMessage = processListMapper.selectById(proofBargain.getId());
        if (processEntityForUnreadMessage.getAuditerStatus() != 100) {
            List hasBeenReadModelList = new ArrayList<>();
            HasBeenReadModel hasBeenReadModel = new HasBeenReadModel();
            hasBeenReadModel.setUsername(proofBargain.getAuditingPerson());
            hasBeenReadModel.setMessageId(proofBargain.getId());
            hasBeenReadModel.setMessageType("1");
            hasBeenReadModelList.add(hasBeenReadModel);
            hasBeenReadMapper.addHasBeenReads(hasBeenReadModelList);
        }
        return "process/myprocess"; // 返回处理结果给前端
    }


    //修改提交接口(成交单)
    @RequestMapping("/proofbargainModifyingDocuments")
    public String proofbargainModifyingDocuments(Model model,@RequestParam("filePath") MultipartFile[] filePath , ProofBargain proofBargain, @AuthenticationPrincipal CustomUserDetails userDetails) throws IOException, ParseException {
//        System.out.println("1075"+proofBargain);
        //为了记录未读消息提醒(messageType = "1")
        ProcessEntity processEntityForUnreadMessage = processListMapper.selectById(proofBargain.getId());
        if (processEntityForUnreadMessage.getAuditerStatus() != 100) {
            List hasBeenReadModelList = new ArrayList<>();
            HasBeenReadModel hasBeenReadModel = new HasBeenReadModel();
            hasBeenReadModel.setUsername(proofBargain.getAuditingPerson());
            hasBeenReadModel.setMessageId(proofBargain.getId());
            hasBeenReadModel.setMessageType("1");
            hasBeenReadModelList.add(hasBeenReadModel);
            hasBeenReadMapper.addHasBeenReads(hasBeenReadModelList);
        }

//        System.out.println("参数1"+proofBargain);

        processListMapper.updateModifyingDocuments(proofBargain.getAuditingPerson(), userMapper.selectName(proofBargain.getAuditingPerson()), proofBargain.getId(), proofBargain.getPaymentWay());
//        System.out.println("1044 filePath = " + proofBargain.getAuditingPerson() + ", proofBargain = " + userMapper.selectName(proofBargain.getAuditingPerson())  );

        /*=====================时间轴相关部分=======================*/
        LocalDateTime currentTime = LocalDateTime.now();
        DateTimeFormatter formDate = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        String formDateTime = currentTime.format(formDate);

        String textNameValue = formDateTime + "; " + userMapper.selectName(proofBargain.getAuditingPerson());
        String statusNameValue = "3";
        //根据ID查询投诉单据
        StatusEntity statusEntity = processStatusMapper.selectById(proofBargain.getId());
        // 寻找一组空字段text与img进行插入
        int groupIndexone = 2;
        String textName = "text" + groupIndexone ;
        String statusName = "status" + groupIndexone;

        try {
            while (true) {
                Field textField = StatusEntity.class.getDeclaredField(textName);
                textField.setAccessible(true); // 设置字段可访问
                Field statusField = StatusEntity.class.getDeclaredField(statusName);
                statusField.setAccessible(true);

                if (textField.get(statusEntity) == null && statusField.get(statusEntity) == null) {
                    // 将获取到的textValue和imgValue插入到一组空字段中
                    textField.set(statusEntity, textNameValue);
                    statusField.set(statusEntity, statusNameValue);

                    // 找到空字段并插入后，修改上一个status字段的值为"1"
                    String prevStatusName = "status" + (groupIndexone-1);
                    Field prevStatusField = StatusEntity.class.getDeclaredField(prevStatusName);
                    prevStatusField.setAccessible(true);
                    if (prevStatusField.get(statusEntity) != null) {
                        prevStatusField.set(statusEntity, "1");
                    }

                    break; // 找到空字段并插入后结束循环
                }

                groupIndexone++;
                textName = "text" + groupIndexone;
                statusName = "status" + groupIndexone;
            }
        } catch (Exception e) {
            e.printStackTrace(); // 处理异常
        }

        // 保存更新后的单据
        processStatusMapper.updateStatus(statusEntity, proofBargain.getId());

        /*=====================时间轴相关部分end=======================*/

        StringBuilder fileAddresses = new StringBuilder();
        for(MultipartFile file:filePath){
            String realaddress= fileService.transfer(file);
            fileAddresses.append(realaddress).append("|");
        }
        if (fileAddresses.length() > 0) {
            fileAddresses.setLength(fileAddresses.length() - 1); // 去掉最后一个"|"
        }
        proofBargain.setFileAddress(fileAddresses.toString());

        ProofBargain oldProofBargain = proofBargainMapper.selectById(proofBargain.getId());
        oldProofBargain.setName(proofBargain.getName());
        oldProofBargain.setSex(proofBargain.getSex());
        oldProofBargain.setTelephone(proofBargain.getTelephone());
        oldProofBargain.setQQ(proofBargain.getQQ());
        oldProofBargain.setSunflower(proofBargain.getSunflower());

        oldProofBargain.setPaymentAmount(proofBargain.getPaymentAmount());
        oldProofBargain.setIdCard(proofBargain.getIdCard());
        oldProofBargain.setFriendDate(proofBargain.getFriendDate());
        oldProofBargain.setTradeTime(proofBargain.getTradeTime());
        oldProofBargain.setFinancingVolume(proofBargain.getFinancingVolume());

        oldProofBargain.setAddress(proofBargain.getAddress());
        oldProofBargain.setSalesman(proofBargain.getSalesman());

        if (proofBargain.getPaymentWay().equals("1")){
            oldProofBargain.setInvoice(proofBargain.getInvoice());
            oldProofBargain.setContract(proofBargain.getContract());
        }else {
            oldProofBargain.setInvoice(null);
            oldProofBargain.setContract(null);
        }

        //备注
        String originalRemarks = oldProofBargain.getRemarks();
        int lastSlashIndex6 = originalRemarks.lastIndexOf("/");
        String newRemarks;
        if (lastSlashIndex6 != -1) {
            newRemarks = originalRemarks.substring(0, lastSlashIndex6 + 1) + proofBargain.getRemarks();
        } else {
            newRemarks = proofBargain.getRemarks();
        }
        oldProofBargain.setRemarks(newRemarks);
        //转账日期
        String originalTransferDate = oldProofBargain.getTransferDate();
        int lastSlashIndex5 = originalTransferDate.lastIndexOf("/");
        String newTransferDate;
        if (lastSlashIndex5 != -1) {
            newTransferDate = originalTransferDate.substring(0, lastSlashIndex5 + 1) + " " + proofBargain.getTransferDate();
        } else {
            newTransferDate = proofBargain.getTransferDate();
        }
        oldProofBargain.setTransferDate(newTransferDate);
        // 收款方式
        String originalPaymentMethod = oldProofBargain.getPaymentMethod();
        int lastSlashIndex = originalPaymentMethod.lastIndexOf("/");
        String newPaymentMethod;
        if (lastSlashIndex != -1) {
            newPaymentMethod = originalPaymentMethod.substring(0, lastSlashIndex + 1) + proofBargain.getPaymentMethod();
        } else {
            newPaymentMethod = proofBargain.getPaymentMethod();
        }
        oldProofBargain.setPaymentMethod(newPaymentMethod);
        //收款方
        String originalPaymentAddress = oldProofBargain.getPaymentAddress();
        int lastSlashIndex1 = originalPaymentAddress.lastIndexOf("/");
        String newPaymentAddress;
        if (lastSlashIndex1 != -1) {
            newPaymentAddress = originalPaymentAddress.substring(0, lastSlashIndex1 + 1) + proofBargain.getPaymentAddress();
        } else {
            newPaymentAddress = proofBargain.getPaymentAddress();
        }
        oldProofBargain.setPaymentAddress(newPaymentAddress);
        //定金日期及金额
        String originalDeposit = oldProofBargain.getDeposit();
        int lastSlashIndex2 = originalDeposit.lastIndexOf("/");
        String newDeposit;
        if (lastSlashIndex2 != -1) {
            newDeposit = originalDeposit.substring(0, lastSlashIndex2 + 1) + proofBargain.getDeposit();
        } else {
            newDeposit = proofBargain.getDeposit();
        }
        oldProofBargain.setDeposit(newDeposit);
        //补款日期及金额
        String originalSupplementaryPayment = oldProofBargain.getSupplementaryPayment();
        int lastSlashIndex4 = originalSupplementaryPayment.lastIndexOf("/");
        String newSupplementaryPayment;
        if (lastSlashIndex4 != -1) {
            newSupplementaryPayment = originalSupplementaryPayment.substring(0, lastSlashIndex4 + 1) + proofBargain.getSupplementaryPayment();
        } else {
            newSupplementaryPayment = proofBargain.getSupplementaryPayment();
        }
        oldProofBargain.setSupplementaryPayment(newSupplementaryPayment);
        //尾款日期及金额
        String originalBalancePayment = oldProofBargain.getBalancePayment();
        int lastSlashIndex3 = originalBalancePayment.lastIndexOf("/");
        String newBalancePayment;
        if (lastSlashIndex3 != -1) {
            newBalancePayment = originalBalancePayment.substring(0, lastSlashIndex3 + 1) + proofBargain.getBalancePayment();
        } else {
            newBalancePayment = proofBargain.getBalancePayment();
        }
        oldProofBargain.setBalancePayment(newBalancePayment);
        //图片路径
        String originalFileAddress = oldProofBargain.getFileAddress();
        String  newFileAddress = originalFileAddress + "|" + proofBargain.getFileAddress();
        newFileAddress = newFileAddress.replaceAll("\\|null", "");
        oldProofBargain.setFileAddress(newFileAddress);
        proofBargain = oldProofBargain;
        model.addAttribute("tanchuang", "yes");
        //存储成交单
        ReturnUser ru = userMapper.findPositonDepartmentNameByName(userDetails.getUsername());
        proofBargain.setPositionName(ru.getPositionName());
        proofBargain.setDepartmentName(ru.getDepartmentName());
//        System.out.println("参数2"+proofBargain);
        proofBargainMapper.updateaddById(proofBargain);
        return "process/myprocess"; // 返回处理结果给前端
    }

    //采购单提交接口
    @RequestMapping ("/purchaseadd")
    public String purchaseadd(@Param("filePath") MultipartFile filePath , PurchaseModel purchaseModel,@AuthenticationPrincipal CustomUserDetails userDetails,Model model) throws IOException, ParseException {
        processListMapper.addPersonAndRealName(purchaseModel.getAuditingPerson(),userMapper.selectName(purchaseModel.getAuditingPerson()),purchaseModel.getId(), purchaseModel.getPaymentWay());
        //文件储存
        if(filePath!=null){
            String realaddress=   fileService.transfer(filePath);
            //存储采购单
            purchaseModel.setFileAddress(realaddress);
        }
        model.addAttribute("tanchuang","yes");
        ReturnUser ru=userMapper.findPositonDepartmentNameByName(userDetails.getUsername());
        purchaseModel.setPositionName(ru.getPositionName());
        purchaseModel.setDepartmentName(ru.getDepartmentName());
        purchaseMapper.insert(purchaseModel);

        // 时间轴相关 在创建单据时插入第一个审核人
        LocalDateTime currentTime = LocalDateTime.now();
        DateTimeFormatter formDate = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        String formDateTime = currentTime.format(formDate);
        String text1 = formDateTime + "; " + userMapper.selectName(purchaseModel.getAuditingPerson());
        processStatusMapper.statusInsert(purchaseModel.getId(),text1);

        //为了记录未读消息提醒(messageType = "1")
        ProcessEntity processEntityForUnreadMessage = processListMapper.selectById(purchaseModel.getId());
        if (processEntityForUnreadMessage.getAuditerStatus() != 100) {
            List hasBeenReadModelList = new ArrayList<>();
            HasBeenReadModel hasBeenReadModel = new HasBeenReadModel();
            hasBeenReadModel.setUsername(purchaseModel.getAuditingPerson());
            hasBeenReadModel.setMessageId(purchaseModel.getId());
            hasBeenReadModel.setMessageType("1");
            hasBeenReadModelList.add(hasBeenReadModel);
            hasBeenReadMapper.addHasBeenReads(hasBeenReadModelList);
        }

//        //一.实现采购单的申请人是审核流程的最后一个人的时候自动抄送给总/副经理
//        List<BaseUser> jlList = new ArrayList<>();//存放查询并经过条件筛选出来需要审核的人
//        List<String>   supplementCopyPersonsLs = new ArrayList<>();//存放查询并经过条件筛选出来需要审核的人的username，补充到需要抄送人的集合中
//        //1.判断审核状态是不是100（是100就是自己为流程的最后一个，自动通过了）
//        ProcessEntity processEntityForAuditerStatus = processListMapper.selectById(purchaseModel.getId());
//        if (processEntityForAuditerStatus.getAuditerStatus().equals(100)){
//            //2.查询总经理跟副总经理（职位为1和2的）
//            jlList.addAll(userMapper.findBypositionId("1"));
//            jlList.addAll(userMapper.findBypositionId("2"));
//            for (String  auditingPerson:processEntityForAuditerStatus.getAuditingPerson().split("\\|")){
//                //3.遍历总经理跟副总经理的集合
//                for (int i = 0;i < jlList.size();i++){
//                    //4.判断审核人中有没有总经理或者是副总经理
//                    if (auditingPerson.equals(jlList.get(i).getUsername())){
//                        jlList.remove(i);
//                    }
//                }
//            }
//            //5.遍历jList,获取到每一个username，放到补充抄送人的集合中
//            for (BaseUser baseUser:jlList){
//                supplementCopyPersonsLs.add(baseUser.getUsername());
//            }
//        }
//        //7.插入抄送
//        if (supplementCopyPersonsLs.size()!= 0){
//            processListMapper.upsertCopy(supplementCopyPersonsLs,purchaseModel.getId());
//
//            //为了记录未读消息提醒(messageType = "3")
//            List hasBeenReadModelListCP = new ArrayList<>();
//            for (String cp:supplementCopyPersonsLs){
//                HasBeenReadModel hasBeenReadModelCP  = new HasBeenReadModel();
//                hasBeenReadModelCP.setUsername(cp);
//                hasBeenReadModelCP.setMessageId(purchaseModel.getId());
//                hasBeenReadModelCP.setMessageType("3");
//                hasBeenReadModelListCP.add(hasBeenReadModelCP);
//            }
//            hasBeenReadMapper.addHasBeenReads(hasBeenReadModelListCP);
//        }
        return "process/processadd";
    }
    //离职单提交接口
    @RequestMapping ("/resignadd")
    public String proofbargainadd(@Param("filePath") MultipartFile filePath ,ResignModel resignModel,@AuthenticationPrincipal CustomUserDetails userDetails,Model model,ComplianceModel complianceModel) throws IOException, ParseException {
        processListMapper.addPersonAndRealName(resignModel.getAuditingPerson(),userMapper.selectName(resignModel.getAuditingPerson()),resignModel.getId(), resignModel.getPaymentWay());
        //文件储存
        if(filePath!=null){
            String realaddress=   fileService.transfer(filePath);
            //存储离职单
            resignModel.setFileAddress(realaddress);
        }
        model.addAttribute("tanchuang","yes");
        ReturnUser ru=userMapper.findPositonDepartmentNameByName(userDetails.getUsername());
        resignModel.setPositionName(ru.getPositionName());
        resignModel.setDepartmentName(ru.getDepartmentName());
        resignMapper.insert(resignModel);
        //一.当离职的提交人为流程审核的最后一个人的时候（也就是自动审核通过，提交的时候的审核状态就是100）修改该用户的在职状态为离职
            //1.查询提交时该离职单的审核状态
            ProcessEntity processEntityForUpdateIsIncumbency = processListMapper.selectById(resignModel.getId());
            //2.判断该离职单的审核状态是不是100
            if (processEntityForUpdateIsIncumbency.getAuditerStatus() == 100){
                //3.调用修改用户在职状态的方法
                userMapper.updateIsIncumbencyByUserName(userDetails.getUsername(),0);
            }

        // 时间轴相关 在创建单据时插入第一个审核人
        LocalDateTime currentTime = LocalDateTime.now();
        DateTimeFormatter formDate = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        String formDateTime = currentTime.format(formDate);
        String text1 = formDateTime + "; " + userMapper.selectName(resignModel.getAuditingPerson());
        processStatusMapper.statusInsert(resignModel.getId(),text1);

        //为了记录未读消息提醒(messageType = "1")
        ProcessEntity processEntityForUnreadMessage = processListMapper.selectById(resignModel.getId());
        if (processEntityForUnreadMessage.getAuditerStatus() != 100) {
            List hasBeenReadModelList = new ArrayList<>();
            HasBeenReadModel hasBeenReadModel = new HasBeenReadModel();
            hasBeenReadModel.setUsername(resignModel.getAuditingPerson());
            hasBeenReadModel.setMessageId(resignModel.getId());
            hasBeenReadModel.setMessageType("1");
            hasBeenReadModelList.add(hasBeenReadModel);
            hasBeenReadMapper.addHasBeenReads(hasBeenReadModelList);
        }
        return  "process/processadd";
    }
    //退款单提交接口
    @RequestMapping ("/refundadd")
    public String refundadd(@Param("filePath") MultipartFile filePath ,RefundModel refundModel,@AuthenticationPrincipal CustomUserDetails userDetails,
                            Model model,@Param("copyPersons")String copyPersons) throws IOException, ParseException {
        if(copyPersons != null && !copyPersons.equals("[]")){
            JSONArray ja=JSONArray.parseArray(copyPersons);
            List<String> copyPersonsLs=new ArrayList<>();
            for(int i=0;i<ja.size();i++){
                JSONObject jsonObject =ja.getJSONObject(i);
                copyPersonsLs.add(jsonObject.getString("value"));
            }
            processListMapper.upsertCopy(copyPersonsLs,refundModel.getId());
            //为了记录未读消息提醒(messageType = "3")
            if(copyPersonsLs.size() != 0){
                List hasBeenReadModelListCP = new ArrayList<>();
                for (String cp:copyPersonsLs){
                    HasBeenReadModel hasBeenReadModelCP  = new HasBeenReadModel();
                    hasBeenReadModelCP.setUsername(cp);
                    hasBeenReadModelCP.setMessageId(refundModel.getId());
                    hasBeenReadModelCP.setMessageType("3");
                    hasBeenReadModelListCP.add(hasBeenReadModelCP);
                }
                hasBeenReadMapper.addHasBeenReads(hasBeenReadModelListCP);
            }

        }
        if (refundModel.getRefundType().equals("1")){
            //退款类型为1（365）那么他的paymentWay应该是4
            processListMapper.addPersonAndRealName(refundModel.getAuditingPerson(),userMapper.selectName(refundModel.getAuditingPerson()),refundModel.getId(), "4");
        }else if (refundModel.getRefundType().equals("2")){
            //退款类型为2（大额）那么他的paymentWay应该是5
            String[] listforCop=defaultCopyMapper.findUserNames(10).split("\\|");
            List<String> supplementCopyPersonsLs=new ArrayList<>();
            for (String i:listforCop) {
                    supplementCopyPersonsLs.add(i);

            }
            //7.插入抄送
            if (supplementCopyPersonsLs.size()!= 0){
                processListMapper.upsertCopy(supplementCopyPersonsLs,refundModel.getId());
                //为了记录未读消息提醒(messageType = "3")
                List hasBeenReadModelListCP = new ArrayList<>();
                for (String cp:supplementCopyPersonsLs){
                    HasBeenReadModel hasBeenReadModelCP  = new HasBeenReadModel();
                    hasBeenReadModelCP.setUsername(cp);
                    hasBeenReadModelCP.setMessageId(refundModel.getId());
                    hasBeenReadModelCP.setMessageType("3");
                    hasBeenReadModelListCP.add(hasBeenReadModelCP);
                }
                hasBeenReadMapper.addHasBeenReads(hasBeenReadModelListCP);
            }
            processListMapper.addPersonAndRealName(refundModel.getAuditingPerson(),userMapper.selectName(refundModel.getAuditingPerson()),refundModel.getId(),"5");
        }

        //文件储存
        if(filePath!=null){
            String realaddress=   fileService.transfer(filePath);
            //存储采购单
            refundModel.setFileAddress(realaddress);
        }
        model.addAttribute("tanchuang","yes");
        ReturnUser ru=userMapper.findPositonDepartmentNameByName(userDetails.getUsername());
        refundModel.setPositionName(ru.getPositionName());
        refundModel.setDepartmentName(ru.getDepartmentName());
        refundModel.setApplyName(userDetails.getRealName());//申请人
        //实际使用期限的时间拼接“-”
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(refundModel.getActualPeriodOfUseStart()).append("——").append(refundModel.getActualPeriodOfUseEnd());
        refundModel.setActualPeriodOfUse(stringBuffer.toString());
        refundMapper.insert(refundModel);

        // 时间轴相关 在创建单据时插入第一个审核人
        LocalDateTime currentTime = LocalDateTime.now();
        DateTimeFormatter formDate = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        String formDateTime = currentTime.format(formDate);
        String text1 = formDateTime + "; " + userMapper.selectName(refundModel.getAuditingPerson());
        processStatusMapper.statusInsert(refundModel.getId(),text1);

        //为了记录未读消息提醒(messageType = "1")
        ProcessEntity processEntityForUnreadMessage = processListMapper.selectById(refundModel.getId());
        if (processEntityForUnreadMessage.getAuditerStatus() != 100) {
            List hasBeenReadModelList = new ArrayList<>();
            HasBeenReadModel hasBeenReadModel = new HasBeenReadModel();
            hasBeenReadModel.setUsername(refundModel.getAuditingPerson());
            hasBeenReadModel.setMessageId(refundModel.getId());
            hasBeenReadModel.setMessageType("1");
            hasBeenReadModelList.add(hasBeenReadModel);
            hasBeenReadMapper.addHasBeenReads(hasBeenReadModelList);
        }
        return  "process/processadd";
    }
    //合规申请提交接口
    @RequestMapping ("/complianceadd")
    public String complianceadd(@AuthenticationPrincipal CustomUserDetails userDetails,@RequestParam("imgfiles") MultipartFile[] imgfiles,@RequestParam("videofiles") MultipartFile[]videofiles,ComplianceModel complianceModel,Model model,@Param("copyPersons")String copyPersons) throws IOException, ParseException {
        JSONArray ja=JSONArray.parseArray(copyPersons);
        List<String> copyPersonsLs=new ArrayList<>();
        for(int i=0;i<ja.size();i++){
            JSONObject jsonObject =ja.getJSONObject(i);
            copyPersonsLs.add(jsonObject.getString("value"));
        }
        processListMapper.addPersonAndRealName(complianceModel.getAuditingPerson(),userMapper.selectName(complianceModel.getAuditingPerson()),complianceModel.getId(), complianceModel.getPaymentWay());
        for(MultipartFile file:imgfiles){
            String realaddress= fileService.transfer(file);
            fileMapper.connectProcessFile(complianceModel.getId(),realaddress);

        }
        //一.实现合规单的申请人是审核流程的最后一个人的时候自动抄送给总/副经理
        List<BaseUser> jlList = new ArrayList<>();//存放查询并经过条件筛选出来需要审核的人
        List<String>   supplementCopyPersonsLs = new ArrayList<>();//存放查询并经过条件筛选出来需要审核的人的username，补充到需要抄送人的集合中
        //1.判断审核状态是不是100（是100就是自己为流程的最后一个，自动通过了）
        ProcessEntity processEntityForAuditerStatus = processListMapper.selectById(complianceModel.getId());
        if (processEntityForAuditerStatus.getAuditerStatus().equals(100)){
            //2.查询总经理跟副总经理（职位为1和2的）
            jlList.addAll(userMapper.findBypositionId("1"));
            jlList.addAll(userMapper.findBypositionId("2"));
            for (String  auditingPerson:processEntityForAuditerStatus.getAuditingPerson().split("\\|")){
                //3.遍历总经理跟副总经理的集合
                for (int i = 0;i < jlList.size();i++){
                    //4.判断审核人中有没有总经理或者是副总经理
                    if (auditingPerson.equals(jlList.get(i).getUsername())){
                        jlList.remove(i);
                    }
                }
            }
            //5.遍历jList,获取到每一个username，放到补充抄送人的集合中
            for (BaseUser baseUser:jlList){
                supplementCopyPersonsLs.add(baseUser.getUsername());
            }
            //6.将supplementCopyPersonsLs这个抄送人集合的补充加到copyPersonsLs这个抄送人集合中
            copyPersonsLs.addAll(supplementCopyPersonsLs);
        }
        //7.插入抄送
        if (copyPersonsLs.size()!= 0){
            processListMapper.upsertCopy(copyPersonsLs,complianceModel.getId());
        }
        //查找合规
        for(MultipartFile file:videofiles){
            String realaddress= fileService.transfer(file);
            fileMapper.connectProcessFile(complianceModel.getId(),realaddress);
        }
        model.addAttribute("tanchuang","yes");
        ReturnUser ru=userMapper.findPositonDepartmentNameByName(userDetails.getUsername());
        complianceModel.setPositionName(ru.getPositionName());
        complianceModel.setDepartmentName(ru.getDepartmentName());
        complianceMapper.insert(complianceModel);

        //为了记录未读消息提醒(messageType = "3")
        if(copyPersonsLs.size() != 0){
            List hasBeenReadModelListCP = new ArrayList<>();
            for (String cp:copyPersonsLs){
                HasBeenReadModel hasBeenReadModelCP  = new HasBeenReadModel();
                hasBeenReadModelCP.setUsername(cp);
                hasBeenReadModelCP.setMessageId(complianceModel.getId());
                hasBeenReadModelCP.setMessageType("3");
                hasBeenReadModelListCP.add(hasBeenReadModelCP);
            }
            hasBeenReadMapper.addHasBeenReads(hasBeenReadModelListCP);
        }

        // 时间轴相关 在创建单据时插入第一个审核人
        LocalDateTime currentTime = LocalDateTime.now();
        DateTimeFormatter formDate = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        String formDateTime = currentTime.format(formDate);
        String text1 = formDateTime + "; " + userMapper.selectName(complianceModel.getAuditingPerson());
        processStatusMapper.statusInsert(complianceModel.getId(),text1);

        //为了记录未读消息提醒(messageType = "1")
        ProcessEntity processEntityForUnreadMessage = processListMapper.selectById(complianceModel.getId());
        if (processEntityForUnreadMessage.getAuditerStatus() != 100) {
            List hasBeenReadModelList = new ArrayList<>();
            HasBeenReadModel hasBeenReadModel = new HasBeenReadModel();
            hasBeenReadModel.setUsername(complianceModel.getAuditingPerson());
            hasBeenReadModel.setMessageId(complianceModel.getId());
            hasBeenReadModel.setMessageType("1");
            hasBeenReadModelList.add(hasBeenReadModel);
            hasBeenReadMapper.addHasBeenReads(hasBeenReadModelList);
        }
        return  "process/processadd";
    }
    //报销申请提交接口
    @RequestMapping ("/reimburseadd")
    public String reimburseadd(@AuthenticationPrincipal CustomUserDetails userDetails,@RequestParam("imgfiles") MultipartFile[] imgfiles,ReimburseModel reimburseModel,Model model) throws IOException, ParseException {
        processListMapper.addPersonAndRealName(reimburseModel.getAuditingPerson(),userMapper.selectName(reimburseModel.getAuditingPerson()),reimburseModel.getId(), reimburseModel.getPaymentWay());
        for(MultipartFile file:imgfiles){
            String realaddress= fileService.transfer(file);
            fileMapper.connectProcessFile(reimburseModel.getId(),realaddress);

        }
        model.addAttribute("tanchuang","yes");
        ReturnUser ru=userMapper.findPositonDepartmentNameByName(userDetails.getUsername());
        reimburseModel.setPositionName(ru.getPositionName());
        reimburseModel.setDepartmentName(ru.getDepartmentName());
        reimburseMapper.insert(reimburseModel);

        // 时间轴相关 在创建单据时插入第一个审核人
        LocalDateTime currentTime = LocalDateTime.now();
        DateTimeFormatter formDate = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        String formDateTime = currentTime.format(formDate);
        String text1 = formDateTime + "; " + userMapper.selectName(reimburseModel.getAuditingPerson());
        processStatusMapper.statusInsert(reimburseModel.getId(),text1);

        //为了记录未读消息提醒(messageType = "1")
        ProcessEntity processEntityForUnreadMessage = processListMapper.selectById(reimburseModel.getId());
        if (processEntityForUnreadMessage.getAuditerStatus() != 100) {
            List hasBeenReadModelList = new ArrayList<>();
            HasBeenReadModel hasBeenReadModel = new HasBeenReadModel();
            hasBeenReadModel.setUsername(reimburseModel.getAuditingPerson());
            hasBeenReadModel.setMessageId(reimburseModel.getId());
            hasBeenReadModel.setMessageType("1");
            hasBeenReadModelList.add(hasBeenReadModel);
            hasBeenReadMapper.addHasBeenReads(hasBeenReadModelList);
        }
        return  "process/processadd";
    }
    //借款申请提交接口
    @RequestMapping ("/loanadd")
    public String loanadd(@Param("filePath") MultipartFile filePath , LoanModel loanModel,@AuthenticationPrincipal CustomUserDetails userDetails,Model model) throws IOException, ParseException {
        processListMapper.addPersonAndRealName(loanModel.getAuditingPerson(),userMapper.selectName(loanModel.getAuditingPerson()),loanModel.getId(), loanModel.getPaymentWay());
        if(filePath!=null){
            String realaddress= fileService.transfer(filePath);
            //存储采购单
            loanModel.setFileAddress(realaddress);
        }
        model.addAttribute("tanchuang","yes");
        ReturnUser ru=userMapper.findPositonDepartmentNameByName(userDetails.getUsername());
        loanModel.setPositionName(ru.getPositionName());
        loanModel.setDepartmentName(ru.getDepartmentName());
        loanModel.setLoanDate(LocalDate.now().toString());
        loanMapper.insert(loanModel);


        // 时间轴相关 在创建单据时插入第一个审核人
        LocalDateTime currentTime = LocalDateTime.now();
        DateTimeFormatter formDate = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        String formDateTime = currentTime.format(formDate);
        String text1 = formDateTime + "; " + userMapper.selectName(loanModel.getAuditingPerson());
        processStatusMapper.statusInsert(loanModel.getId(),text1);


        //为了记录未读消息提醒(messageType = "1")
        ProcessEntity processEntityForUnreadMessage = processListMapper.selectById(loanModel.getId());
        if (processEntityForUnreadMessage.getAuditerStatus() != 100) {
            List hasBeenReadModelList = new ArrayList<>();
            HasBeenReadModel hasBeenReadModel = new HasBeenReadModel();
            hasBeenReadModel.setUsername(loanModel.getAuditingPerson());
            hasBeenReadModel.setMessageId(loanModel.getId());
            hasBeenReadModel.setMessageType("1");
            hasBeenReadModelList.add(hasBeenReadModel);
            hasBeenReadMapper.addHasBeenReads(hasBeenReadModelList);
        }
        return  "process/processadd";
    }
    //365推送申请提交（推送）接口
    @RequestMapping ("/push365add")
    public String push365add( ThreeSixFivePushModel push365Model,@AuthenticationPrincipal CustomUserDetails userDetails,Model model) throws IOException, ParseException {
        // 获取当前的日期和时间
        LocalDateTime now = LocalDateTime.now();
        // 定义日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 格式化日期时间
        String formattedDateTime = now.format(formatter);
        // 将格式化后的日期时间设置到报告中
        push365Model.setReportDate(formattedDateTime);
        String id=UUID.randomUUID().toString().toLowerCase();
        push365Model.setId(id);
        StringJoiner joiner = new StringJoiner(",");
        for (String method : push365Model.getPaymentMethods()) {
            if (method != null) {
                joiner.add(method);
            }
        }
        push365Model.setPaymentMethod(joiner.toString());
        //通过当天的日期去查询最新插入的序号
        Integer maxId=push365Mapper.selectMaxId();
        if(maxId==null){
            maxId=0;
        }
        push365Model.setSerialNumber(maxId+1);
        push365Mapper.insert(push365Model);
        model.addAttribute("userDetails",userDetails);
        return  "pushinfo/pushinfo";
    }
    //删除流程
    @RequestMapping ("/delete")
    @ResponseBody
    public Result delete(@RequestParam("id") String id,@AuthenticationPrincipal CustomUserDetails userDetails) throws IOException, ParseException {
        processListMapper.delete(id);
        //为了清除，审核流程最后一个人点击单据（创建了单据）后，又退出的时候的未读消息的清除
        hasBeenReadMapper.deleteHasBeenRead(userDetails.getUsername(),id);
        return  Result.success();
    }
    //流程审核接口
    @RequestMapping (value = "/auditingresult")
    @ResponseBody
    public Result auditingresult(@Param("auditing") Boolean auditing,@Param("id") String id,@Param("auditingperson") String auditingperson,@Param("rejectReason") String rejectReason,
                                 @Param("copyPersons")String copyPersons,@AuthenticationPrincipal CustomUserDetails userDetails,@RequestParam(value = "isLoan",defaultValue = "") String isLoan,@RequestParam(value = "loan",defaultValue = "") String loan) throws IOException {
//        System.out.println("1648"+ copyPersons);
        LocalDateTime currentTime = LocalDateTime.now(); //获取当前的日期和时间
        DateTimeFormatter formDate = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        String formDateTime = currentTime.format(formDate);
        String auditingPersonRealName =  userMapper.selectName(auditingperson);
        JSONArray ja=JSONArray.parseArray(copyPersons);
        List<String> copyPersonsLs=new ArrayList<>();
        for(int i=0;i<ja.size();i++){
            JSONObject jsonObject =ja.getJSONObject(i);
            copyPersonsLs.add(jsonObject.getString("value"));
        }
        ProcessEntity pe= processListMapper.selectById(id);
        Date enddate=new Date();
        Date startdate=pe.getApplyTime();
        //审核状态（进行到第几步）
        Integer order=pe.getAuditerStatus()+1;
        Integer Auditer=pe.getAuditerStatus();
        Integer Count=pe.getAuditingCount();

          if(auditing){
              if(Auditer == Count){
                  /*=====================时间轴相关部分(审核完成)=======================*/

                  String textNameValue = formDateTime + "; " + auditingPersonRealName;
                  String statusNameValue = "3";
                  //根据ID查询单据
                  StatusEntity statusEntity = processStatusMapper.selectById(id);
                  // 寻找一组空字段text与statusName进行插入
                  int groupIndexone = 2;
                  String textName = "text" + groupIndexone ;
                  String statusName = "status" + groupIndexone;

                  try {
                      while (true) {
                          Field textField = StatusEntity.class.getDeclaredField(textName);
                          textField.setAccessible(true); // 设置字段可访问
                          Field statusField = StatusEntity.class.getDeclaredField(statusName);
                          statusField.setAccessible(true);

                          if (textField.get(statusEntity) == null && statusField.get(statusEntity) == null) {
//                              // 将获取到的textValue和imgValue插入到一组空字段中
//                              textField.set(statusEntity, textNameValue);
//                              statusField.set(statusEntity, statusNameValue);

                              // 找到空字段，修改上一个status字段的值为"1"
                              String prevStatusName = "status" + (groupIndexone-1);
                              Field prevStatusField = StatusEntity.class.getDeclaredField(prevStatusName);
                              prevStatusField.setAccessible(true);
                              if (prevStatusField.get(statusEntity) != null) {
                                  prevStatusField.set(statusEntity, "1");
                              }

                              break; // 找到空字段并插入后结束循环
                          }

                          groupIndexone++;
                          textName = "text" + groupIndexone;
                          statusName = "status" + groupIndexone;
                      }
                  } catch (Exception e) {
                      e.printStackTrace(); // 处理异常
                  }

                  // 保存更新后的单据
                  processStatusMapper.updateStatus(statusEntity, id);

                  /*========================end(审核完成)==============================*/


              }else {
                  /*=====================时间轴相关部分(审核通过)=======================*/

                  String textNameValue = formDateTime + "; " + auditingPersonRealName;
                  String statusNameValue = "3";
                  //根据ID查询单据
                  StatusEntity statusEntity = processStatusMapper.selectById(id);
                  // 寻找一组空字段text与statusName进行插入
                  int groupIndexone = 2;
                  String textName = "text" + groupIndexone ;
                  String statusName = "status" + groupIndexone;

                  try {
                      while (true) {
                          Field textField = StatusEntity.class.getDeclaredField(textName);
                          textField.setAccessible(true); // 设置字段可访问
                          Field statusField = StatusEntity.class.getDeclaredField(statusName);
                          statusField.setAccessible(true);

                          if (textField.get(statusEntity) == null && statusField.get(statusEntity) == null) {
                              // 将获取到的textValue和imgValue插入到一组空字段中
                              textField.set(statusEntity, textNameValue);
                              statusField.set(statusEntity, statusNameValue);

                              // 找到空字段并插入后，修改上一个status字段的值为"1"
                              String prevStatusName = "status" + (groupIndexone-1);
                              Field prevStatusField = StatusEntity.class.getDeclaredField(prevStatusName);
                              prevStatusField.setAccessible(true);
                              if (prevStatusField.get(statusEntity) != null) {
                                  prevStatusField.set(statusEntity, "1");
                              }

                              break; // 找到空字段并插入后结束循环
                          }

                          groupIndexone++;
                          textName = "text" + groupIndexone;
                          statusName = "status" + groupIndexone;
                      }
                  } catch (Exception e) {
                      e.printStackTrace(); // 处理异常
                  }

                  // 保存更新后的单据
                  processStatusMapper.updateStatus(statusEntity, id);

                  /*========================end(审核通过)==============================*/

              }

              //查找当前状态并判断是否是结束
              processListMapper.auditingtrue(id);

              if(pe.getAuditingCount()>pe.getAuditerStatus()){
                  processListMapper.updateAuditingPersonAndRealName(auditingperson,auditingPersonRealName,id,new Date());

                  //为了记录未读消息提醒(messageType = "1")
                  List hasBeenReadModelList = new ArrayList<>();
                  HasBeenReadModel hasBeenReadModel  = new HasBeenReadModel();
                  hasBeenReadModel.setUsername(auditingperson);
                  hasBeenReadModel.setMessageId(id);
                  hasBeenReadModel.setMessageType("1");
                  hasBeenReadModelList.add(hasBeenReadModel);
                  hasBeenReadMapper.addHasBeenReads(hasBeenReadModelList);

              }
              Integer count=pe.getAuditingCount();
              if(order>count){
                  long days=(enddate.getTime()-startdate.getTime())/(24*60*60*1000);
                 processListMapper.Completed(id,enddate,days,new Date());
                  //一.实现（合规）（采购）在最后一个人审核通过时，自动抄送给审核人中不涉及到的总经理跟副总经理。（请假）经理级别以上人员请假，在最后一个人审核通过时，也自动抄送
                  if (auditing){//0.判断是否是审核通过，不是驳回（驳回不走下面的流程）
                      //1.先判断流程是否是最后一步（判断当前状态是否是结束状态）
                      if (order>count){
                          //2.判断单据的类型
                          List<BaseUser> jlList = new ArrayList<>();//存放查询并经过条件筛选出来需要审核的人
                          List<String>   supplementCopyPersonsLs = new ArrayList<>();//存放查询并经过条件筛选出来需要审核的人的username，补充到需要抄送人的集合中
                          if (pe.getProcessType() == 7 ){
                              //2.1单据类型为合规单或者采购单
                              //2.3.查询总经理跟副总经理（职位为1和2的）
                              jlList.addAll(userMapper.findBypositionId("1"));
                              jlList.addAll(userMapper.findBypositionId("2"));
                              //2.2.将审核人的字符段按“|”拆开并遍历
                              for (String  auditingPerson:pe.getAuditingPerson().split("\\|")){
                                  //2.4.遍历总经理跟副总经理的集合
                                  for (int i = 0;i < jlList.size();i++){
                                      //2.5.判断审核人中有没有总经理或者是副总经理
                                      if (auditingPerson.equals(jlList.get(i).getUsername())){
                                          jlList.remove(i);
                                      }
                                  }
                              }
                          }else if (pe.getProcessType() == 0 ){
                              //2.2单据类型为请假单（经理级别以上人员请假，在最后一个人审核通过时，也自动抄送）
                              //2.3通过申请人来查询他的职位
                              List<BaseUser> userList = userMapper.findByUserName(pe.getApplyName());
                              //2.4遍历userList，获取到申请人的职位
                              for (int i = 0;i<userList.size();i++){
                                  Integer positonId = userList.get(i).getPositionId();
                                  //2.5将申请人的职位做筛选（是否是经理以上级别：包括部门经理，区域经理）
                                  List<Integer> specialLeaves = new ArrayList() {{
                                      //区域经理
                                      add(4);add(9);
                                      //部门经理
                                      add(5);add(10);add(14);add(18);add(22);add(25);add(27);add(31);add(35);add(43);
                                  }};
                                  for (Integer specialLeavePositionId:specialLeaves){
                                      //2.6判断申请人的职位是否在特殊请假人集合中
                                      if (positonId.equals(specialLeavePositionId)){
                                          //2.7查询到总经理，并插入到存放查询并经过条件筛选出来需要审核的人的集合中
                                          jlList.addAll(userMapper.findBypositionId("1"));
                                      }
                                  }
                              }
                          }
                          //3.遍历jList,获取到每一个username，放到补充抄送人的集合中
                          for (BaseUser baseUser:jlList){
                              supplementCopyPersonsLs.add(baseUser.getUsername());
                          }
                          //4.将supplementCopyPersonsLs这个抄送人集合的补充加到copyPersonsLs这个抄送人集合中
                          copyPersonsLs.addAll(supplementCopyPersonsLs);
                      }
                  }

              }
          }else {

              // 已完成审核显示(只限投诉单据) 修改了processListMapper.auditingfalse方法
              String completeReview = pe.getCompleteReview();
              if (completeReview != null){
                  // 判断 completeReview 中是否包含 auditingPerson 的值
                  if (!completeReview.contains(userDetails.getUsername())) {
                      completeReview = completeReview +"|"+userDetails.getUsername();
                  }
              }else {
                  completeReview = userDetails.getUsername();
              }
//              System.out.println("1470更新后的 completeReview 值为: " + completeReview);


              String applyRealName = pe.getApplyRealName();
              long days=(enddate.getTime()-startdate.getTime())/(24*60*60*1000);
              processListMapper.auditingfalse(applyRealName,id,enddate,days,rejectReason,new Date(),completeReview);

//              System.out.println("1480: "+ userDetails.getRealName() + " rejectReason: " + rejectReason + " ID: " + id);

              // 把驳回原因插入到新表 id,驳回原因rejectReason,审核人,驳回状态reviewStatus为2


              /*=====================时间轴相关部分(驳回)=======================*/

              String prevText = formDateTime + "; " + userDetails.getRealName() + " 驳回原因: " + rejectReason; // 下面的驳回修改

              String textNameValue = formDateTime + "; " + pe.getApplyRealName(); // 驳回后插入的单据申请人
              String statusNameValue = "3";
              //根据ID查询投诉单据
              StatusEntity statusEntity = processStatusMapper.selectById(id);
              // 寻找一组空字段text与img进行插入
              int groupIndexone = 2;
              String textName = "text" + groupIndexone ;
              String statusName = "status" + groupIndexone;

              try {
                  while (true) {
                      Field textField = StatusEntity.class.getDeclaredField(textName);
                      textField.setAccessible(true); // 设置字段可访问
                      Field statusField = StatusEntity.class.getDeclaredField(statusName);
                      statusField.setAccessible(true);
                      if (textField.get(statusEntity) == null && statusField.get(statusEntity) == null) {
                          // 将获取到的textValue和imgValue插入到一组空字段中
                          textField.set(statusEntity, textNameValue);
                          statusField.set(statusEntity, statusNameValue);

                          // 找到空字段并插入后，修改上一个status字段的值为"1"
                          String prevTextName = "text" + (groupIndexone-1);
                          String prevStatusName = "status" + (groupIndexone-1);
                          Field prevTextField = StatusEntity.class.getDeclaredField(prevTextName);
                          prevTextField.setAccessible(true);
                          Field prevStatusField = StatusEntity.class.getDeclaredField(prevStatusName);
                          prevStatusField.setAccessible(true);
                          if (prevStatusField.get(statusEntity) != null && prevTextField.get(statusEntity) != null) {
                              prevTextField.set(statusEntity, prevText);
                              prevStatusField.set(statusEntity, "2");
                          }

                          break; // 找到空字段并插入后结束循环
                      }

                      groupIndexone++;
                      textName = "text" + groupIndexone;
                      statusName = "status" + groupIndexone;
                  }
              } catch (Exception e) {
                  e.printStackTrace(); // 处理异常
              }

              // 保存更新后的单据
              processStatusMapper.updateStatus(statusEntity, id);

              /*========================end(驳回)==============================*/


          }
        if (pe.getProcessType() == 4 ){
            if(isLoan.length()>0&&loan.length()>0){
                purchaseMapper.update(loan,isLoan,id);
            }
        }
        //将抄送的人给加入到表中
        if(copyPersonsLs.size()>0){
            processListMapper.upsertCopy(copyPersonsLs,id);

            //为了记录未读消息提醒(messageType = "3")
            List hasBeenReadModelListCP = new ArrayList<>();
            for (String cp:copyPersonsLs){
                HasBeenReadModel hasBeenReadModelCP  = new HasBeenReadModel();
                hasBeenReadModelCP.setUsername(cp);
                hasBeenReadModelCP.setMessageId(id);
                hasBeenReadModelCP.setMessageType("3");
                hasBeenReadModelListCP.add(hasBeenReadModelCP);
            }
            hasBeenReadMapper.addHasBeenReads(hasBeenReadModelListCP);
        }

        return  Result.success();
    }

      //获取第几步的是什么职位
      String getauditingposition(Integer order,String allstring){
          String[] strings=allstring.split("\\|");
          String i="0";
           if(order<strings.length){
               i=strings[order];
               return  i;
           }
          return null;
      }
    //获取第几步的是什么职位
    List<String> strarrtolist(String s){
        JSONArray ja=JSONArray.parseArray(s);
        List<String> ls=new ArrayList<>();
        for(int i=0;i<ja.size();i++){
            JSONObject jsonObject =ja.getJSONObject(i);
            ls.add(jsonObject.getString("value"));
        }
        return ls;
    }

}